/* eslint-disable max-lines */
import React from 'react';
import routes from './routes';
import * as api from './api';
import * as Enum from '../Enum';
import styles from './style.css';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {getValidateStatus} from './utils';
import {approveValidate} from './validator';
import {injectIntl, formatMessage} from './intl';
import {tableSearch, approveOrder} from './actions';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {formatDateTime, conventEnumValueToString} from '../utils';
import {Card, Button, Row, Col, Form, Table, Radio, AutoComplete, Spin} from 'antd';
import {FORM_OPTIONS, DATETIME_FORMAT, FILES_API, TABLE, FORM_OPTIONS_L, FORM_ROW_OPTIONS,
    PAGINATION_OPTIONS, PAGE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT} from '../constants';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const {Description} = DescriptionList;
export class ApprovePanel extends React.PureComponent {
    state = {
        data: {},
        loading: false,
        isValidate: false,
        currentCondition: {},
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
    };
    componentDidMount() {
        this.setState({loading: true});
        api.getDetail(this.props.id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data.details,
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    onIsPassChange = event => {
        const value = event.target.value;
        const data = Object.assign({}, this.state.data, {
            approvedResult: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    };
    onApproveCommentChange = value => {
        const data = Object.assign({}, this.state.data, {
            approveComment: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    };
    onQuery = condition => {
        this.setState({loading: true});
        api.getDetail(this.props.id, condition).then(res => {
            if(res.ok)
                this.setState({
                    loading: false,
                    message: '',
                    data: res.data.details,
                    currentCondition: condition
                });
            else
                this.setState({
                    loading: false,
                    data: [],
                    message: res.message
                });
        });
    }
    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        condition.pageSize = PAGE.smallSize;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }
    onSubmit = () => {
        const data = this.state.data;
        const condition = {
            id: this.props.id,
            approvedResult: data.approvedResult,
            approveComment: data.approveComment,
            rowVersion: data.rowVersion
        };
        const isValid = approveValidate(condition);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        this.setState({loading: true});
        approveOrder(condition).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.successReturn();
        });
    };
    render() {
        const {data, loading} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const fileList = data.attachments ? data.attachments.map(item => (<Description key={item.fileId}>
            <a icon="download" href={`${FILES_API.files}/${item.fileId}`} size="small">
                {item.fileName}</a></Description>)) : '';
        const columns = [
            {
                title: formatMessage({
                    id: 'approvePanel.details.usedPartCode',
                    defaultMessage: '旧件编号'
                }),
                dataIndex: 'usedPartCode'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.usedPartName',
                    defaultMessage: '旧件名称'
                }),
                dataIndex: 'usedPartName'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.newPartCode',
                    defaultMessage: '新件编号'
                }),
                dataIndex: 'newPartCode'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.newPartName',
                    defaultMessage: '新件名称'
                }),
                dataIndex: 'newPartName'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.isCaused',
                    defaultMessage: '是否主因件'
                }),
                dataIndex: 'isCaused',
                render: text => text ? '是' : '否'
            },
        ];
        const fuliaoColumns = [
            {
                title: formatMessage({
                    id: 'approvePanel.details.fuliaoPartCode',
                    defaultMessage: '辅料编号'
                }),
                dataIndex: 'usedPartCode'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.fuliaoPartName',
                    defaultMessage: '辅料名称'
                }),
                dataIndex: 'usedPartName'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.unit',
                    defaultMessage: '计量单位'
                }),
                dataIndex: 'unit'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.minQty',
                    defaultMessage: '最小包装数'
                }),
                dataIndex: 'minQty'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.materialFee',
                    defaultMessage: '辅料金额'
                }),
                dataIndex: 'materialFee'
            },
        ];
        const apColumns = [
            {
                title: formatMessage({
                    id: 'approvePanel.details.approvedResult',
                    defaultMessage: '审核结果'
                }),
                dataIndex: 'approvedResult',
                render: text => conventEnumValueToString(Enum.technologyActivityApprovedResult, text)
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.approveComment',
                    defaultMessage: '审核意见'
                }),
                dataIndex: 'approveComment'
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.approveTime',
                    defaultMessage: '审核时间'
                }),
                dataIndex: 'approveTime',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'approvePanel.details.approverName',
                    defaultMessage: '审核人名称'
                }),
                dataIndex: 'approverName'
            },
        ];
        const vehicleColumns = [
            {
                title: formatMessage({
                    id: 'newPanel.vehicle.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin'
            },
            {
                title: formatMessage({
                    id: 'newPanel.vehicle.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country',
            },
            {
                title: formatMessage({
                    id: 'newPanel.vehicle.engineCode',
                    defaultMessage: '发动机号'
                }),
                dataIndex: 'engineCode',
            },
            {
                title: formatMessage({
                    id: 'newPanel.vehicle.transmissionSn',
                    defaultMessage: '变速箱号'
                }),
                dataIndex: 'transmissionSn',
            },
            {
                title: formatMessage({
                    id: 'newPanel.vehicle.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
            },
        ];
        return (
            <div className={styles.detail}>
                <Spin spinning={loading || this.props.loading}>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.card.title',
                            defaultMessage: '技术升级信息'
                        })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.code',
                                    defaultMessage: '技术升级编号'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.code}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.serviceName',
                                    defaultMessage: '技术升级主题'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.serviceName}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.brandCode',
                                    defaultMessage: '品牌'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.brandCode}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.dealerCode',
                                    defaultMessage: '总代'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.dealerCode}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.content',
                                    defaultMessage: '主要内容'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.content}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.vehicleCategory',
                                    defaultMessage: '车辆类别'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {conventEnumValueToString(Enum.vehicleCategory, data.vehicleCategory)}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.checkLabor',
                                    defaultMessage: '检查工时'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.checkLabor}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS_L.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.checkChangeLabor',
                                    defaultMessage: '检查工时+更换工时'
                                })}
                                {...FORM_OPTIONS_L.item}>
                                    {data.checkChangeLabor}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.checkChangeAssistLabor',
                                    defaultMessage: '检查工时+更换工时+辅助工时'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.checkChangeAssistLabor}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.isClaimPart',
                                    defaultMessage: '是否索赔备件'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.isClaimPart ? '是' : '否'}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.isClaimAssist',
                                    defaultMessage: '是否索赔辅料'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.isClaimAssist ? '是' : '否'}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.startTime',
                                    defaultMessage: '开始时间'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {formatDateTime(data.startTime, DATETIME_FORMAT)}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.endTime',
                                    defaultMessage: '技术升级截止日期'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {formatDateTime(data.endTime, DATETIME_FORMAT)}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.supplierCode',
                                    defaultMessage: '供应商编号'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.supplierCode}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.dutyUnitCode',
                                    defaultMessage: '主要责任部门'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.dutyUnitCode}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.serviceTotal',
                                    defaultMessage: '活动总数'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.serviceTotal}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.immatureTotal',
                                    defaultMessage: '未完成数'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.immatureTotal}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.total',
                                    defaultMessage: '完成数'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.total}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.isDealerApply',
                                    defaultMessage: '是否总代申请'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.isDealerApply ? '是' : '否'}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.isDelay',
                                    defaultMessage: '是否已延期'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.isDelay ? '是' : '否'}
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'approvePanel.form.remark',
                                    defaultMessage: '备注'
                                })}
                                {...FORM_OPTIONS.item}>
                                    {data.remark}
                                </FormItem>
                            </Col>
                        </Row>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.attachments.title',
                            defaultMessage: '附件清单'
                        })}
                        bordered={false}>
                        {fileList.length ? <DescriptionList col={1} size="large">
                            {fileList}
                        </DescriptionList> : formatMessage({
                            id: 'approvePanel.attachments.noData',
                            defaultMessage: '暂无附件'
                        })}
                    </Card>
                    {data.isClaimAssist
                        ? <Card
                            title={formatMessage({
                                id: 'approvePanel.technologyActivityMaterial.title',
                                defaultMessage: '技术升级维修辅料清单'
                            })}
                            bordered={false}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="id"
                                columns={fuliaoColumns}
                                pagination={false}
                                dataSource={data.technologyActivityMaterial}
                                {...TABLE} />
                        </Card>
                        : <Card
                            title={formatMessage({
                                id: 'approvePanel.details.title',
                                defaultMessage: '技术升级维修材料清单'
                            })}
                            bordered={false}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="id"
                                columns={columns}
                                pagination={false}
                                dataSource={data.noIsTechnologyActivityMaterialList}
                                {...TABLE} />
                        </Card>}
                    <Card
                        title={formatMessage({
                            id: 'detailPanel.vehicle.title',
                            defaultMessage: '技术升级指定车辆清单'
                        })}
                        bordered={false}>
                        <Table
                            className="white-space-nowrap"
                            rowKey="id"
                            columns={vehicleColumns}
                            loading={loading || this.props.loading}
                            pagination={{
                                total: data.technologyActivityVehicleList ? data.technologyActivityVehicleList.totalElements : 0,
                                current: pageIndex + 1,
                                pageSize,
                                onShowSizeChange: this.onPageSizeChange,
                                onChange: this.onPageIndexChange,
                                ...PAGINATION_OPTIONS
                            }}
                            locale={{
                                emptyText: this.state.message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                            }}
                            dataSource={data.technologyActivityVehicleList ? data.technologyActivityVehicleList.content : []}
                            {...TABLE}/>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.technologyActivityResultDetails.title',
                            defaultMessage: '技术升级审核历史清单'
                        })}
                        bordered={false}>
                        <Table
                            className="white-space-nowrap"
                            rowKey="id"
                            columns={apColumns}
                            pagination={false}
                            dataSource={data.technologyActivityResultList}
                            {...TABLE}/>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.approveInfo',
                            defaultMessage: '审核信息'
                        })}>
                        <Row>
                            <Col>
                                <FormItem
                                    label={formatMessage({
                                        id: 'approvePanel.approvedResult',
                                        defaultMessage: '审核状态'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}
                                    validateStatus={getValidateStatus(
                                        this.state.isValidate,
                                        data.approvedResult
                                    )}
                                    required>
                                    <RadioGroup
                                        name="approvedResult"
                                        onChange={this.onIsPassChange}
                                        value={data.approvedResult}>
                                        <Radio value={1}>
                                            {formatMessage({
                                                id: 'approvePanel.yes',
                                                defaultMessage: '审核通过'
                                            })}
                                        </Radio>
                                        <Radio value={2}>
                                            {formatMessage({
                                                id: 'approvePanel.bohui',
                                                defaultMessage: '驳回'
                                            })}
                                        </Radio>
                                        <Radio value={3}>
                                            {formatMessage({
                                                id: 'approvePanel.no',
                                                defaultMessage: '审核不通过	'
                                            })}
                                        </Radio>
                                    </RadioGroup>
                                </FormItem>
                            </Col>
                            <Col>
                                <FormItem
                                    label={formatMessage({
                                        id: 'approvePanel.approveComment',
                                        defaultMessage: '审核意见'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}
                                    validateStatus={getValidateStatus(
                                        this.state.isValidate,
                                        data.approveComment
                                    )}
                                    required>
                                    <AutoComplete
                                        onChange={this.onApproveCommentChange}
                                        value={data.approveComment}
                                        filterOption={(inputValue, option) =>
                                            option.props.children
                                                .toUpperCase()
                                                .indexOf(
                                                    inputValue.toUpperCase()
                                                ) !== -1}
                                        dataSource={this.state.approveComments}/>
                                </FormItem>
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.btn.submit',
                                defaultMessage: '提交'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'approvePanel.btn.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

ApprovePanel.propTypes = {
    loading: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    successReturn: PropTypes.func,
};

const mapStateToProps = state => ({
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
});
const mapDispatchToProps = (dispatch, props) => ({
    onCancel: () => {
        props.history.push(routes.query.url());
    },
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ApprovePanel));
